package com.ebupt.migu.music.common.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.HttpAsyncResponseConsumerFactory;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;

import com.ebupt.migu.music.common.entity.StaticUser;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * User: lizm Date: 2019/9/18
 */
@Slf4j
public class RestClientUtils {

    public static final long BUFFER_SIZE = 520 * 1024 * 1024;

    /**
     * es查询
     * 
     * @param restClient 客户端
     * @param sql DSL
     * @param esPath 路径
     * @param requestType 请求方式
     * @return
     */
    public static String getESDtats(RestClient restClient, String sql, String esPath, String requestType) {
        if (null != restClient && !StringUtils.isBlank(sql) && !StringUtils.isBlank(esPath)) {
            HttpEntity entity = new NStringEntity(sql, ContentType.APPLICATION_JSON);
            String result = null;
            Map<String, String> params = Collections.emptyMap();
            HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory consumerFactory =
                new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory((int)BUFFER_SIZE);
            try {
                // Response indexResponse = restClient.performRequest(null == requestType ? "GET" : requestType, esPath,
                // params, entity, consumerFactory);
                Request request = new Request("GET", esPath);
                request.setEntity(entity);
                Response indexResponse = restClient.performRequest(request);
                result = EntityUtils.toString(indexResponse.getEntity());
            } catch (IOException var8) {
                var8.printStackTrace();
            }
            return result;
        } else {
            return null;
        }
    }

    /**
     * es反查uid
     * 
     * @param msisdn 手机号码
     * @return
     */
    public static List<StaticUser> getUser(RestClient restClient, String msisdn, String esIndex, String esType) {
        // 拼装dsl json语句
        StringBuilder requestBody = new StringBuilder();
        requestBody.append("{");
        requestBody.append("\"size\":10000,");
        requestBody.append("\"query\":{\"match\":{\"msisdn\":").append(msisdn).append("}}");
        requestBody.append("}");
        // es路径
        // String esPath = String.format("/%s/%s/%s", esIndex,esType, "_search");
        String esPath = String.format("/%s/%s", esIndex, "_search");
        String result = getESDtats(restClient, requestBody.toString(), esPath, "GET");
        JSONObject jsonObject = new JSONObject(result);
        JSONObject hits = jsonObject.getJSONObject("hits");
        Integer total = Integer.parseInt(hits.getStr("total"));
        JSONArray hitsArray = hits.getJSONArray("hits");
        JSONObject source = null;
        int id = 0;
        List<StaticUser> userList = new ArrayList<StaticUser>();
        if (total == 0) {
            StaticUser user = new StaticUser();
            user.setMsisdn(msisdn);
            user.setUid("");
            user.setIdfa("");
            user.setImei("");
            userList.add(user);
        } else {
            // ES反查结果集
            List<StaticUser> esUserList = new ArrayList<StaticUser>();
            // 存到黑白名单的记录
            // 只要uid、idfa、imei，三者有一个不一样，就认为是一条记录
            List<StaticUser> esUserTrueList = new ArrayList<StaticUser>();
            for (int i = 0; i < hitsArray.size(); i++) {
                JSONObject obj = hitsArray.getJSONObject(i);
                source = obj.getJSONObject("_source");
                String uid = source.getStr("uid");
                String imei = source.getStr("imei");
                String idfa = source.getStr("idfa");
                StaticUser item = new StaticUser();
                item.setUid(uid);
                item.setImei(imei);
                item.setIdfa(idfa);
                item.setMsisdn(msisdn);
                esUserList.add(item);
            }
            StaticUser esUserTemp = new StaticUser();
            int isNullNum = 0;
            for (int i = 0; i < esUserList.size(); i++) {
                StaticUser esUser = esUserList.get(i);
                if (esUserTrueList.contains(esUser)) {
                    // 存在不插入
                } else {// esUserTrueList不存在该对象
                        // 不存在插入
                        // 排除三个字段都为空的情况
                    if (StringUtils.isBlank(esUser.getUid()) && StringUtils.isBlank(esUser.getImei())
                        && StringUtils.isBlank(esUser.getIdfa())) {
                        isNullNum++;
                    } else {
                        esUserTrueList.add(esUser);
                    }
                }
            }
            if (isNullNum == esUserList.size()) {// 返回的多条记录uid、imei、idfa全部为空字段，此时存一条
                StaticUser user = new StaticUser();
                user.setMsisdn(msisdn);
                user.setUid("");
                user.setIdfa("");
                user.setImei("");
                userList.add(user);
            } else {
                userList = esUserTrueList;
            }
        }
        return userList;
    }

}
